package com.ang.serverSendEvent;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/sse")
public class SseController {

    @GetMapping("/getSSEContent")
    public SseEmitter getSSEContent() {
        SseEmitter emitter = new SseEmitter();

        // 模拟定期发送消息
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(() -> {
            try {
                // 创建 SSE 事件并发送消息
                SseEmitter.SseEventBuilder event = SseEmitter.event()
                        .data("Message at " + System.currentTimeMillis())
                        .id(String.valueOf(System.currentTimeMillis()))
                        .reconnectTime(3000);
                emitter.send(event);
            } catch (IOException e) {
                // 出现异常时完成 SSE 连接
                emitter.completeWithError(e);
            }
        }, 0, 2, TimeUnit.SECONDS);

        // 处理 SSE 连接完成事件
        emitter.onCompletion(() -> System.out.println("SSE connection completed."));
        // 处理 SSE 连接超时事件
        emitter.onTimeout(() -> {
            System.out.println("SSE connection timed out.");
            emitter.complete();
        });
        // 处理 SSE 连接错误事件
        emitter.onError((e) -> {
            System.out.println("SSE connection error: " + e.getMessage());
            emitter.completeWithError(e);
        });

        return emitter;
    }
}
